import Taro, {Component, Config, getCurrentPages} from '@tarojs/taro'
import {AtAvatar, AtList, AtListItem, AtBadge, AtCurtain} from "taro-ui"
import {View, Text, Image, Button} from '@tarojs/components'
import {observer, inject} from '@tarojs/mobx'
import Stores from '../../stores/storeIdentifier'
import SessionStore from "../../stores/sessionStore"
import AuthenticationStore from '../../stores/authenticationStore'
import './index.scss'
import TabBar from "../../component/tabBar/tabBar"
import {GetCurrentLoginInformations} from '../../services/session/dto/getCurrentLoginInformations'
import {OrderCountDto} from '../../services/order/dto/orderCountDto'
import OrderStore from '../../stores/orderStore'
import ModuleTypeIds from '../../services/dto/moduleTypeIds'

export interface IIndexProps {
  sessionStore: SessionStore,
  authenticationStore: AuthenticationStore,
  orderStore: OrderStore
}

@inject(Stores.SessionStore, Stores.AuthenticationStore, Stores.OrderStore)
@observer
class Index extends Component<IIndexProps> {
  state = {
    currentLogin: new GetCurrentLoginInformations(),
    orderCount: new OrderCountDto(),
    isOpened: false
  }

  constructor(props: any) {
    super(props);
  }

  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '个人中心',
    backgroundColor: '#fff',
    navigationBarBackgroundColor: '#fff',
    navigationBarTextStyle: 'black'
  }

  async componentWillMount() {
    await this.getCurrentUser();
    await this.getMyOrderCount()
  }

  async getMyOrderCount() {
    if (Taro.getStorageSync('access_token')) {
      await this.props.orderStore.getMyOrderCount([ModuleTypeIds.Product])
      let orderCount = this.props.orderStore.orderCount
      this.setState({orderCount: orderCount})
    }
  }

  componentWillReact() {
    console.log('componentWillReact')
  }

  async componentDidShow() {
    let pages = getCurrentPages()
    let prev = pages[pages.length - 1]


    if (prev.data.isAuthorize) {
      prev.setData({
        isAuthorize: false
      })

      await this.getCurrentUser()
    }
  }

  gotoLogin() {
    if (!Taro.getStorageSync('access_token')) {
      Taro.navigateTo({
        url: '/pages/passport/index',
      })
    }
  }

  async getCurrentUser() {
    await this.props.sessionStore.getCurrentLoginInformations();
    const {currentLogin} = this.props.sessionStore;

    this.setState({currentLogin: currentLogin});
  }

  gotoOrder() {
    if (!Taro.getStorageSync('access_token')) {
      Taro.navigateTo({
        url: '/pages/passport/index',
      })
    } else
      Taro.navigateTo({url: '/pages/profile/order/index'})
  }

  gotoLink = (value, index) => {
    if (!Taro.getStorageSync('access_token')) {
      Taro.navigateTo({
        url: '/pages/passport/index',
      })
      return
    }
    let nav = value.toString();
    let url = '/pages/profile/order/index?status='
    let status
    switch (nav) {
      case "1":
        status = 10
        break;
      case "2":
        status = 20
        break;
      case "3":
        status = 100
        break;
      case "0":
        status = 0
        break;
    }
    Taro.navigateTo({
      url: url + status
    })
  }

  gotoAddress() {
    if (!Taro.getStorageSync('access_token')) {
      Taro.navigateTo({
        url: '/pages/passport/index',
      })
      return
    }
    Taro.navigateTo({
      url: '/pages/profile/address/index'
    })
  }

  gotoStore() {
    if (!Taro.getStorageSync('access_token')) {
      Taro.navigateTo({
        url: '/pages/passport/index',
      })
      return
    }
    Taro.navigateTo({
      url: '/pages/profile/store/index'
    })
  }

  logout = async () => {
    await this.props.authenticationStore.logout();

    Taro.redirectTo({url: '/pages/index/index'})
  };
  handleChange () {
    this.setState({
      isOpened: true
    })
  }
  onClose () {
    this.setState({
      isOpened: false
    })
  }
  render() {

    return (
      <View className='profile-wrap'>
        <View className='center-header' onClick={this.gotoLogin}>
          <AtAvatar className='center-img' circle
                    image={this.state.currentLogin.user.avatar || 'http://www.51yuanliang.com/images/miniapp/user.jpg'}
          />
          {this.state.currentLogin.user && <Text>{this.state.currentLogin.user.nickName}</Text>}
          {!this.state.currentLogin.user && <Text>未登录</Text>}
        </View>

        <View className='profile-panel'>
          <View className='profile-panel-header ratina-bd bd-b'>
            <Text className='strong'>服务记录</Text>
            {/*<Text className='more' onClick={this.gotoOrder}>查看全部</Text>*/}
          </View>
          <View className='profile-panel-body'>
            <View className='grid-box'>
              <View className='grid-item' onClick={this.gotoLink.bind(this, 0)}>
                <AtBadge value={this.state.orderCount.WaitPay != 0 ? this.state.orderCount.WaitPay : ''} maxValue={99}>
                  <Image className='item-img' mode='scaleToFill' src='http://www.51yuanliang.com/images/miniapp/step1.gif'/>
                </AtBadge>
                <Text>待付款</Text>
              </View>
              <View className='grid-item ratina-bd bd-l' onClick={this.gotoLink.bind(this, 1)}>
                <AtBadge value={this.state.orderCount.PaidAndWaitShip != 0 ? this.state.orderCount.PaidAndWaitShip : ''}
                         maxValue={99}>
                  <Image className='item-img' mode='scaleToFill' src='http://www.51yuanliang.com/images/miniapp/step2.gif'/>
                </AtBadge>
                <Text>待发货</Text>
              </View>
              <View className='grid-item ratina-bd bd-l' onClick={this.gotoLink.bind(this, 2)}>
                <AtBadge
                  value={this.state.orderCount.ShippedAndWaitReceipt != 0 ? this.state.orderCount.ShippedAndWaitReceipt : ''}
                  maxValue={99}>
                  <Image className='item-img' mode='scaleToFill' src='http://www.51yuanliang.com/images/miniapp/step3.gif'/>
                </AtBadge>
                <Text>待收货</Text>
              </View>
              <View className='grid-item ratina-bd bd-l' onClick={this.gotoLink.bind(this, 3)}>
                <AtBadge value={this.state.orderCount.WaitComment != 0 ? this.state.orderCount.WaitComment : ''}
                         maxValue={99}>
                  <Image className='item-img' mode='scaleToFill' src='http://www.51yuanliang.com/images/miniapp/step4.gif'/>
                </AtBadge>
                <Text>已完成</Text>
              </View>
            </View>
          </View>
        </View>
        <AtList>
          <AtListItem
            title='收货地址'
            arrow='right'
            onClick={this.gotoAddress}
            thumb='http://www.51yuanliang.com/images/miniapp/icon-dizhi.svg'
          />
          <AtListItem
            title='商务合作'
            arrow='right'
            onClick={this.handleChange.bind(this)}
            thumb='http://www.51yuanliang.com/images/miniapp/icon-hezuo.svg'
          />
          <Button className='trans-btn' size='mini' open-type='contact'>
            <AtListItem
              title='在线客服'
              arrow='right'
              thumb='http://www.51yuanliang.com/images/miniapp/icon-kefu.svg'
            />
          </Button>
          <Button className='trans-btn' size='mini' open-type='feedback'>
            <AtListItem
              title='意见反馈'
              arrow='right'
              thumb='http://www.51yuanliang.com/images/miniapp/icon-fankui.svg'
            />
          </Button>
        </AtList>
        <AtCurtain
          isOpened={this.state.isOpened}
          onClose={this.onClose.bind(this)}
        >
          <Image
            style='width:100%;height:250px'
            src='http://www.51yuanliang.com/images/miniapp/hezuo.png'
            mode='aspectFit'
          />
        </AtCurtain>

        <View className='disc'>每件事都有个好的结局，如果还不够美好，那就是还未结束...</View>
        <TabBar nowPage='profile'/>
      </View>
    )
  }
}

export default Index
